package ssh

import (
	"fmt"

	"path/filepath"

	"time"

	"io/ioutil"
	"log"
	"os"

	"bytes"

	"golang.org/x/crypto/ssh"
)

func (sh Ssh) LoginEcs(ip, shell string) string {
	host := fmt.Sprintf("%s:22", ip)
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		fmt.Println(err)
	}
	filePathStr := fmt.Sprintf("%s/%s", dir, "sshKey.txt")
	content, err := ioutil.ReadFile(filePathStr)
	if err != nil {
		fmt.Println(err)
	}
	key := content

	signer, err := ssh.ParsePrivateKey(key)
	if err != nil {
		log.Fatalf("parse key failed:%v", err)
	}

	config := &ssh.ClientConfig{
		User:            "root",
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
		Timeout:         time.Second * 3600,
	}
	client, err := ssh.Dial("tcp", host, config)
	if err != nil {
		log.Fatal("Failed to dial: ", err)
	}
	defer client.Close()

	session, err := client.NewSession()
	if err != nil {
		log.Fatal("Failed to create session: ", err)
	}
	defer session.Close()

	var b bytes.Buffer
	session.Stdout = &b

	if err := session.Run(shell); err != nil {
		log.Fatal("Failed to run: " + err.Error())
	}
	return b.String()
}
